# -*- coding: utf-8 -*-
"""
系统集成管理API

按照模块文档2.5节要求提供系统集成功能的API接口
"""

from typing import List, Dict, Any, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from pydantic import BaseModel, Field
from datetime import datetime
import logging

from ....core.database import get_db
from ....auth.jwt_auth import get_current_active_user
from ....services.integration_service import IntegrationService
from ....services.api_service import ApiService
from ....services.rbac_service import PermissionDecorator
from ....core.exceptions import ValidationError, BusinessError
from ....core.dto import ResponseDTO

logger = logging.getLogger(__name__)
router = APIRouter()


# ==================== 数据模型 ====================

class IntegrationConfigRequest(BaseModel):
    """集成配置请求"""
    integration_type: str = Field(..., description="集成类型: email/sms/payment/storage")
    config_data: Dict[str, Any] = Field(..., description="配置数据")

class IntegrationActionRequest(BaseModel):
    """集成操作请求"""
    action: str = Field(..., description="操作类型: create/update/delete/enable/disable")
    integration_type: str = Field(..., description="集成类型")
    config_data: Optional[Dict[str, Any]] = Field(None, description="配置数据")

class SyncDataRequest(BaseModel):
    """数据同步请求"""
    integration_type: str = Field(..., description="集成类型")
    sync_type: str = Field("full", description="同步类型: full/incremental")

class ConnectionTestRequest(BaseModel):
    """连接测试请求"""
    integration_type: str = Field(..., description="集成类型")
    config_data: Optional[Dict[str, Any]] = Field(None, description="测试配置（可选）")

class AccessRuleRequest(BaseModel):
    """访问控制规则请求"""
    action: str = Field(..., description="操作类型: create/update/delete/enable/disable")
    access_config: Dict[str, Any] = Field(..., description="访问控制配置")

class ApiReportRequest(BaseModel):
    """API报告请求"""
    report_type: str = Field(..., description="报告类型: usage/security/performance/error")
    time_range: int = Field(24, description="时间范围(小时)")
    filters: Optional[Dict[str, Any]] = Field(None, description="筛选条件")


# ==================== 第三方集成API ====================

@router.get("/integrations", response_model=ResponseDTO[Dict], summary="获取集成列表")
@PermissionDecorator.require_permission("system.integration", "read")
async def get_integration_list(
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """获取第三方集成配置列表"""
    try:
        integration_service = IntegrationService(db)
        
        result = integration_service.get_integration_list()
        
        return ResponseDTO[Dict](
            success=True,
            message="获取集成列表成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取集成列表失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取集成列表失败"
        )


@router.post("/integrations/manage", response_model=ResponseDTO[Dict], summary="管理集成配置")
@PermissionDecorator.require_permission("system.integration", "write")
async def manage_integration(
    request: IntegrationActionRequest,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """管理第三方集成配置"""
    try:
        integration_service = IntegrationService(db)
        
        result = await integration_service.manage_integrations(
            action=request.action,
            integration_type=request.integration_type,
            config_data=request.config_data or {},
            operator=current_user.get("username", "unknown")
        )
        
        return ResponseDTO[Dict](
            success=True,
            message=f"集成{request.action}操作成功",
            data=result
        )
        
    except (ValidationError, BusinessError) as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"管理集成失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="管理集成失败"
        )


@router.post("/integrations/test", response_model=ResponseDTO[Dict], summary="测试集成连接")
@PermissionDecorator.require_permission("system.integration", "test")
async def test_integration_connection(
    request: ConnectionTestRequest,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """测试第三方服务连接"""
    try:
        integration_service = IntegrationService(db)
        
        result = await integration_service.test_connections(
            integration_type=request.integration_type,
            config_data=request.config_data
        )
        
        return ResponseDTO[Dict](
            success=result.get("success", False),
            message=result.get("message", "连接测试完成"),
            data=result
        )
        
    except (ValidationError, BusinessError) as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"测试连接失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="测试连接失败"
        )


@router.post("/integrations/sync", response_model=ResponseDTO[Dict], summary="数据同步")
@PermissionDecorator.require_permission("system.integration", "sync")
async def sync_integration_data(
    request: SyncDataRequest,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """执行数据同步"""
    try:
        integration_service = IntegrationService(db)
        
        result = await integration_service.sync_data(
            integration_type=request.integration_type,
            sync_type=request.sync_type,
            operator=current_user.get("username", "unknown")
        )
        
        return ResponseDTO[Dict](
            success=result.get("status") == "completed",
            message="数据同步完成" if result.get("status") == "completed" else "数据同步失败",
            data=result
        )
        
    except (ValidationError, BusinessError) as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"数据同步失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="数据同步失败"
        )


# ==================== API接口管理API ====================

@router.get("/api/monitoring", response_model=ResponseDTO[Dict], summary="API监控数据")
@PermissionDecorator.require_permission("system.api", "read")
async def get_api_monitoring(
    time_range: int = Query(24, ge=1, le=168, description="时间范围(小时)"),
    group_by: str = Query("endpoint", description="分组方式: endpoint/user/method/status"),
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """获取API监控数据"""
    try:
        api_service = ApiService(db)
        
        result = await api_service.monitor_apis(
            time_range=time_range,
            group_by=group_by
        )
        
        return ResponseDTO[Dict](
            success=True,
            message="获取API监控数据成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取API监控数据失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取API监控数据失败"
        )


@router.get("/api/statistics", response_model=ResponseDTO[Dict], summary="API统计数据")
@PermissionDecorator.require_permission("system.api", "read")
async def get_api_statistics(
    time_range: int = Query(24, ge=1, le=168, description="时间范围(小时)"),
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """获取API统计数据"""
    try:
        api_service = ApiService(db)
        
        result = await api_service.get_api_statistics(time_range=time_range)
        
        return ResponseDTO[Dict](
            success=True,
            message="获取API统计数据成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取API统计数据失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取API统计数据失败"
        )


@router.get("/api/access-rules", response_model=ResponseDTO[Dict], summary="获取访问控制规则")
@PermissionDecorator.require_permission("system.api", "read")
async def get_access_rules(
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """获取API访问控制规则列表"""
    try:
        api_service = ApiService(db)
        
        result = api_service.get_access_rules()
        
        return ResponseDTO[Dict](
            success=True,
            message="获取访问控制规则成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取访问控制规则失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取访问控制规则失败"
        )


@router.post("/api/access-rules", response_model=ResponseDTO[Dict], summary="管理访问控制规则")
@PermissionDecorator.require_permission("system.api", "write")
async def manage_access_rules(
    request: AccessRuleRequest,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """管理API访问控制规则"""
    try:
        api_service = ApiService(db)
        
        result = await api_service.manage_access(
            action=request.action,
            access_config=request.access_config,
            operator=current_user.get("username", "unknown")
        )
        
        return ResponseDTO[Dict](
            success=True,
            message=f"访问控制规则{request.action}操作成功",
            data=result
        )
        
    except (ValidationError, BusinessError) as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"管理访问控制规则失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="管理访问控制规则失败"
        )


@router.post("/api/reports", response_model=ResponseDTO[Dict], summary="生成API报告")
@PermissionDecorator.require_permission("system.api", "report")
async def generate_api_reports(
    request: ApiReportRequest,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """生成API使用报告"""
    try:
        api_service = ApiService(db)
        
        result = await api_service.generate_reports(
            report_type=request.report_type,
            time_range=request.time_range,
            filters=request.filters
        )
        
        return ResponseDTO[Dict](
            success=True,
            message=f"{request.report_type}报告生成成功",
            data=result
        )
        
    except (ValidationError, BusinessError) as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"生成API报告失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="生成API报告失败"
        )